import pytz
from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Avg
from django.utils import timezone

from apps.evaluation.models import Evaluation_List, SmartLifeSupportCenter_BranchOffice, \
    DigitalIntelligence_Branch_office, SmartLifeSupportCenter_BusinessDepartment, DigitalIntelligence_BusinessDepartment
from apps.system.models import User
from extensions.serializers import *


class SmartLifeSupportCenter_BranchOfficeSerializer(BaseSerializer):
    #参评人姓名
    reviewer_name = CharField(source='reviewer.name', read_only=True, label='参评人姓名')
    #参评人公司
    reviewer_company = CharField(source='reviewer.company.name', read_only=True, label='参评人公司')

    class Meta:
        model = SmartLifeSupportCenter_BranchOffice
        fields =  "__all__"

    def create(self, validated_data):
        validated_data['reviewer'] = self.context['request'].user
        return super().create(validated_data)


class DigitalIntelligence_Branch_officeSerializer(BaseSerializer):
    #参评人姓名
    reviewer_name = CharField(source='reviewer.name', read_only=True, label='参评人姓名')
    #参评人公司
    reviewer_company = CharField(source='reviewer.company.name', read_only=True, label='参评人公司')

    class Meta:
        model = DigitalIntelligence_Branch_office
        fields =  "__all__"

    def create(self, validated_data):
        validated_data['reviewer'] = self.context['request'].user
        return super().create(validated_data)


class SmartLifeSupportCenter_BusinessDepartmentSerializer(BaseSerializer):
    #参评人姓名
    reviewer_name = CharField(source='reviewer.name', read_only=True, label='参评人姓名')
    #参评人公司
    reviewer_company = CharField(source='reviewer.company.name', read_only=True, label='参评人公司')

    class Meta:
        model = SmartLifeSupportCenter_BusinessDepartment
        fields =  "__all__"

    def create(self, validated_data):
        validated_data['reviewer'] = self.context['request'].user
        return super().create(validated_data)


class DigitalIntelligence_BusinessDepartmentSerializer(BaseSerializer):
    #参评人姓名
    reviewer_name = CharField(source='reviewer.name', read_only=True, label='参评人姓名')
    #参评人公司
    reviewer_company = CharField(source='reviewer.company.name', read_only=True, label='参评人公司')
    class Meta:
        model = DigitalIntelligence_BusinessDepartment
        fields =  "__all__"

    def create(self, validated_data):
        validated_data['reviewer'] = self.context['request'].user
        return super().create(validated_data)


class Evaluation_ListSerializer(BaseSerializer):
    evaluation_name = CharField(source='evaluation.name', read_only=True, label='评测名称')
    path = CharField(source='evaluation.path', read_only=True, label='评测路径')
    has_reviewer = SerializerMethodField()
    api = CharField(source='evaluation.api', read_only=True, label='评测名称')
    model = CharField(source='evaluation.model', read_only=True, label='评测名称')
    evaluation_item_id = SerializerMethodField()
    #是否超时
    is_timeout = SerializerMethodField()
    class Meta:
        model = Evaluation_List
        fields = "__all__"


    def get_has_reviewer(self, obj):
        current_user = self.context['request'].user
        evaluation_model = obj.evaluation.model
        rel_name = f"{evaluation_model}_evaluation_item"
        records = getattr(obj, rel_name).all()
        return any(bo.reviewer == current_user for bo in records)

    def get_evaluation_item_id(self, obj):
        current_user = self.context['request'].user
        evaluation_model = obj.evaluation.model
        rel_name = f"{evaluation_model}_evaluation_item"
        records = getattr(obj, rel_name).all()
        for bo in records:
            if bo.reviewer == current_user:
                return bo.id
        return None

    def get_is_timeout(self, obj):
        #获取当前时间
        now = timezone.now().date()
        #获取评测的结束时间
        end_time = obj.end_time
        #获取评测的开始时间
        start_time = obj.start_time
        #计算当前时间是否大于开始时间和小于结束时间
        if now >= start_time and now <= end_time:
            return False
        return True




class Evaluation_ResultSerializer(BaseSerializer):
    evaluation_name = CharField(source='evaluation.name', read_only=True, label='评测名称')
    path = CharField(source='evaluation.path', read_only=True, label='评测路径')
    api = CharField(source='evaluation.api', read_only=True, label='评测名称')
    model = CharField(source='evaluation.model', read_only=True, label='评测名称')
    #平均分
    average_score = SerializerMethodField()
    class Meta:
        model = Evaluation_List
        fields = "__all__"

    def get_average_score(self, obj):
        evaluation_model = obj.evaluation.model
        rel_name = f"{evaluation_model}_evaluation_item"
        # 使用Django的聚合函数计算平均分
        average_score = getattr(obj, rel_name).aggregate(Avg('total_score'))['total_score__avg']
        # 保留average_score两位小数
        if average_score:
            return round(average_score, 2)
        return average_score
        # records = getattr(obj, rel_name).all()
        # #获取records中的total_score的平均值
        # total_score = 0
        # for bo in records:
        #     total_score += bo.total_score
        # if len(records) != 0:
        #     return total_score/len(records)
        # return None


class Evaluation_ManageSerializer(BaseSerializer):
    evaluation_name = CharField(source='evaluation.name', read_only=True, label='评测名称')
    path = CharField(source='evaluation.path', read_only=True, label='评测路径')
    api = CharField(source='evaluation.api', read_only=True, label='评测名称')
    model = CharField(source='evaluation.model', read_only=True, label='评测名称')
    class Meta:
        model = Evaluation_List
        fields = "__all__"


class Evaluation_SituationSerializer(ModelSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司名称')
    has_reviewer = SerializerMethodField()
    created_at = SerializerMethodField()
    class Meta:
        model = User
        fields = ['id', 'username', 'name', 'is_active', 'company_name','phone','has_reviewer','created_at']

    def get_has_reviewer(self, obj):
        user_id = obj.id
        request = self.context['request']
        model_name = request.query_params.get('model', None)
        item_id = request.query_params.get('evaluation_item_id', None)
        if model_name and item_id:
            full_model_name = f'evaluation.{model_name}'
            ModelClass = apps.get_model(full_model_name)
            # 查询是否存在符合条件的对象
            res=ModelClass.objects.filter(evaluation_item_id=item_id, reviewer_id=user_id).first()
            if res:
                return True
            # 如果找到符合条件的对象，返回True
            else:
                return False
        return False

    def get_created_at(self, obj):
        user_id = obj.id
        request = self.context['request']
        model_name = request.query_params.get('model', None)
        item_id = request.query_params.get('evaluation_item_id', None)
        datetime_format = "%Y-%m-%d %H:%M:%S"  # 您想要的时间格式
        target_timezone = pytz.timezone('Asia/Shanghai')  # 指定您需要的时区
        if model_name and item_id:
            full_model_name = f'evaluation.{model_name}'
            ModelClass = apps.get_model(full_model_name)
            # 查询是否存在符合条件的对象
            res=ModelClass.objects.filter(evaluation_item_id=item_id, reviewer_id=user_id).first()
            if res:
                created_at_localized = timezone.localtime(res.created_at, target_timezone)
                # 将转换后的时间转换为指定的时间格式
                created_at_formatted = created_at_localized.strftime(datetime_format)
                return created_at_formatted
            # 如果找到符合条件的对象，返回True
            else:
                return None
        return None




__all__ = [
    'Evaluation_ListSerializer',
]